package xworker.lang.actions.code;

import org.xmeta.ActionContext;
import org.xmeta.Thing;
import org.xmeta.cache.ThingEntry;

public class ThingAttribueCode {
    ThingEntry parentEntry;
    String attributeName;
    Thing actionThing;

    public ThingAttribueCode(Thing parent, String attributeName, CodeThingFactory codeThingFactory){
        this.attributeName = attributeName;
        parentEntry = new ThingEntry(parent);

        actionThing = codeThingFactory.create();

        actionThing.set("name", attributeName);
        actionThing.getMetadata().setPath(parent.getMetadata().getPath() + "/@fakeCode_" + attributeName);
        actionThing.set("code", parent.getString(attributeName));
        actionThing.setParent(parent);

    }

    public Object execute(ActionContext actionContext){
        if(parentEntry.isChanged()){
            actionThing.set("code", parentEntry.getThing().getString(attributeName));
        }

        return actionThing.getAction().run(actionContext);
    }

    /**
     * 把模型的指定属性作为代码执行，会根据代码类型生成相应的模型并缓存到模型上。
     */
    public static Object execute(Thing thing, String attributeName, CodeThingFactory codeThingFactory, ActionContext actionContext){
        String key = "_facke_code_" + attributeName;
        ThingAttribueCode codeAction = thing.getData(key);
        if(codeAction == null) {

            codeAction = new ThingAttribueCode(thing, attributeName, codeThingFactory);
            thing.setData(key, codeAction);
        }

        return codeAction.execute(actionContext);
    }
}
